package com.supply.dl.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.supply.dl.R;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalPositionAdapter;
import com.supply.dl.app.adapter.RecyclerViewDivider;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.BaseObserver;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.OperateCompanyInfo;
import com.supply.dl.bean.OperateFeeduInfo;
import com.supply.dl.bean.OperateModle;
import com.supply.dl.bean.WorkNotesBean;
import com.supply.dl.utils.DialogUtils;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.utils.Utils;
import com.supply.dl.utils.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作业记录
 * <p>
 * Author:  tian <br/>
 * Time:  2018/7/30 23:03
 */
public class OperateRemarkActivity extends BaseActivity {

    /**
     * 工厂id 来源订单对应工厂(发货作业对应stoOutFactoryId,收货作业对应stoInFactoryId)
     */
    private String factoryId;

    @BindView(R.id.recylerView)
    RecyclerView recyclerView;

    /**
     * 适配器
     */
    private NormalPositionAdapter<WorkNotesBean> adapter;

    /**
     * 显示的数据源
     */
    private ArrayList<WorkNotesBean> remarks;
    /**
     * 上个界面传过来的数据
     */
    private ArrayList<WorkNotesBean> intentRemarks;

    /**
     * 当前操作的 作业记录
     */
    private WorkNotesBean currentOperate;

    /**
     * 当前选择的 作业公司
     */
    private OperateCompanyInfo currentOperateCompanyInfo;
    private String totalWeight = "";

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_work_task_remark;
    }

    @Override
    protected void initView() {
        setRightInVisible();

        factoryId = getIntent().hasExtra("factoryId") ? getIntent().getStringExtra("factoryId") : "";

        showLeftBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collectRemarks();
            }
        });
        intentRemarks = (ArrayList<WorkNotesBean>)getIntent().getSerializableExtra("OperateRemark");
        totalWeight = getIntent().getStringExtra("TotolWeight");
        remarks = new ArrayList<>();
        if(intentRemarks == null || intentRemarks.size()<=0){
            remarks.add(new WorkNotesBean());
        }else{
            remarks.addAll(intentRemarks);
        }


        adapter = new NormalPositionAdapter<WorkNotesBean>(this, remarks) {
            @Override
            protected void convert(ViewHolder holder, final WorkNotesBean data, int position) {
                holder.setText(R.id.remark_no_tv, "记录" + (position + 1));
                holder.setText(R.id.work_company_tv, data.getDepart());
                holder.setText(R.id.worker_tv, data.getJobUser());
                holder.setText(R.id.work_mode_tv, data.getJobMode());
                holder.setText(R.id.work_feilv_tv, data.getJobConstMoney());
                holder.setText(R.id.work_count_tv, data.getJobAmount());
                holder.setText(R.id.work_weight_et, data.getJobWeight());
                holder.setText(R.id.work_volume_et, data.getJobVolume());
                holder.setText(R.id.work_remark_et, data.getRemark());

                EditText work_count_tv = holder.getView(R.id.work_count_tv);

                work_count_tv.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setJobAmount(s.toString());
                    }
                });

                EditText work_weight_et = holder.getView(R.id.work_weight_et);

                work_weight_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setJobWeight(s.toString());
                    }
                });
                EditText work_volume_et = holder.getView(R.id.work_weight_et);
                work_volume_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setJobVolume(s.toString());
                    }
                });
                EditText work_remark_et = holder.getView(R.id.work_weight_et);
                work_remark_et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if (StringUtils.isCanUse(s.toString()))
                            data.setRemark(s.toString());
                    }
                });

                holder.getView(R.id.delete_remark_img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogUtils.showDialog(OperateRemarkActivity.this, "提示", "确定删除记录吗?",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        remarks.remove(data);
                                        adapter.notifyDataSetChanged();
                                    }
                                }).show();
                    }
                });

                //扫码
                holder.getView(R.id.zr_code_img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Utils.startScanActivity(OperateRemarkActivity.this);
                    }
                });


                //作业公司的选择
                holder.getView(R.id.work_company_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tentToSelect(AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT, data);
                    }
                });

                //作业人员的选择
                holder.getView(R.id.worker_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tentToSelect(AppConfig.BaseDataAction.OPERATE_PERSON_SELECT, data);
                    }
                });

                //作业模式的选择
                holder.getView(R.id.work_mode_tv).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tentToSelect(AppConfig.BaseDataAction.OPERATE_MODL_SELECT, data);
                    }
                });


            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_work_remark;
            }
        };

        recyclerView.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL, 20, getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }



    @Override
    protected void initData(Bundle savedInstanceState) {
        setTitleShow("作业记录");
    }

    /**
     * 进行跳转
     *
     * @param action
     * @param wb
     */
    private void tentToSelect(String action, WorkNotesBean wb) {

        currentOperate = wb;

        Intent intent = new Intent(OperateRemarkActivity.this, OperateSelectActivity.class);
        intent.putExtra("action", action);

        //选 作业人员，携带作业公司id
        if (AppConfig.BaseDataAction.OPERATE_COMPANY_SELECT.equals(action))
            intent.putExtra("factoryId", factoryId);

        //选 作业人员，携带作业公司id
        if (AppConfig.BaseDataAction.OPERATE_PERSON_SELECT.equals(action) && currentOperate != null) {
            if (!StringUtils.isCanUse(currentOperate.getDepartId())) {
                Toast.makeText(this, "请先选择作业公司!", Toast.LENGTH_SHORT).show();
                return;
            }
            intent.putExtra("companyId", currentOperate.getDepartId());
        }

        startActivityForResult(intent, 2001);
    }

    @OnClick({R.id.add_remark_btn, R.id.btn_sure})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.add_remark_btn:
                remarks.add(new WorkNotesBean());
                adapter.notifyDataSetChanged();
                break;

            case R.id.btn_sure:
                collectRemarks();
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            collectRemarks();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /**
     * 数据的最后采集打包
     */
    private void collectRemarks() {

        if (remarks.size() == 0) {
            finish();
            return;
        }

        boolean isComlete = true;
        double total = 0.00;
        //数据完整性的检查
        for (int i = 0; i < remarks.size(); i++) {
            if (!StringUtils.isCanUse(remarks.get(i).getDepartId()) || !StringUtils.isCanUse(remarks.get(i).getJobModeIds())
                    || !StringUtils.isCanUse(remarks.get(i).getUserIds()) || !StringUtils.isCanUse(remarks.get(i).getJobWeight())
                    || !StringUtils.isCanUse(remarks.get(i).getJobAmount()) || !StringUtils.isCanUse(remarks.get(i).getFeeIds())) {
                isComlete = false;
                break;
            }else{
                total += Double.parseDouble(remarks.get(i).getJobWeight());
            }
        }

        if (!isComlete) {
            DialogUtils.showDialog(OperateRemarkActivity.this, "提示", "记录有不完整项离去将丢失记录?", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).show();

            return;
        }
        try {
            if(!TextUtils.isEmpty(totalWeight)) {
                if (total > (Double.parseDouble(totalWeight)*2)) {
                    ToastUtil.showToast(OperateRemarkActivity.this, "订单作业大于总吨数");
                    return;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        DialogUtils.showDialog(OperateRemarkActivity.this, "提示", "确定选择吗?", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                onSureSelect();
            }
        }).show();
    }


    /**
     * 确定选择
     */
    private void onSureSelect() {
        Intent intent = new Intent();
        intent.putExtra("remarks", remarks);
        this.setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 2001){ //跳转普通界面
            if (data == null)
                return;

            Serializable operateSelectData = data.hasExtra("selectBean") ? data.getSerializableExtra("selectBean") : null;
            Serializable operateSelectDatas = data.hasExtra("selectBeans") ? data.getSerializableExtra("selectBeans") : null;

            //选择的是公司
            if (operateSelectData != null) {
                currentOperateCompanyInfo = (OperateCompanyInfo) operateSelectData;
                currentOperate.setDepart(currentOperateCompanyInfo.getOperateCompany());
                currentOperate.setDepartId(currentOperateCompanyInfo.getId());

                adapter.notifyDataSetChanged();
                return;
            }

            if (operateSelectDatas != null) {
                ArrayList templist = (ArrayList) operateSelectDatas;

                //选择作业人员
                if (templist.get(0) instanceof OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean) {
                    String operatePersonIds = "";
                    String operatePersonNames = "";

                    for (OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean item :
                            (ArrayList<OperateCompanyInfo.BasOperateTeamListBean.BasOperatePersonListBean>) templist) {
                        operatePersonIds = StringUtils.isCanUse(operatePersonIds) ? operatePersonIds + "," + item.getId() : item.getId();
                        operatePersonNames = StringUtils.isCanUse(operatePersonNames) ? operatePersonNames + "," + item.getPersonName() : item.getPersonName();
                    }

                    currentOperate.setUserIds(operatePersonIds);
                    currentOperate.setJobUser(operatePersonNames);
                    adapter.notifyDataSetChanged();
                }
                //选择模式
                else if (templist.get(0) instanceof OperateModle) {
                    String operateModeIds = "";
                    String operateModeNames = "";

                    for (OperateModle op : (ArrayList<OperateModle>) templist) {
                        operateModeIds = StringUtils.isCanUse(operateModeIds) ? operateModeIds + "," + op.getId() : op.getId();
                        operateModeNames = StringUtils.isCanUse(operateModeNames) ? operateModeNames + "," + op.getModeName() : op.getModeName();
                    }
                    currentOperate.setJobModeIds(operateModeIds);
                    currentOperate.setJobMode(operateModeNames);
                    adapter.notifyDataSetChanged();
                }


                //注意了，当有选择作业公司作业模式时候，需要对作业费率进行查询
                getOperateFeedu();
            }
        }else{ //否则跳转扫描界面返回
            //扫码
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
                } else {
                    String content = result.getContents();
                    if (StringUtils.isBlank(content)) return;
                    if (content.contains("http://") || content.contains("https://")) {
                        Uri uri = Uri.parse(content);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(this, "扫码成功："+content, Toast.LENGTH_LONG).show();
                    }
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }






    }

    /**
     * 查询作业费率,参数为死参数
     * <p>有数据参数
     * companyId=e9c60573-5f7e-40d5-8120-4be85f8dbafc   modeId=23
     */
    private void getOperateFeedu() {
        if (!StringUtils.isCanUse(currentOperate.getDepartId())
                || !StringUtils.isCanUse(currentOperate.getJobModeIds()))
            return;

        // TODO: 参数被写死？
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        mApiService.getOperateFeede(currentOperate.getDepartId(), currentOperate.getJobModeIds())
//        mApiService.getOperateFeede("e9c60573-5f7e-40d5-8120-4be85f8dbafc", "23")
                .compose(RxSchedulers.<BaseInfo<List<OperateFeeduInfo>>>compose(this))
                .subscribe(new BaseObserver<List<OperateFeeduInfo>>() {
                    @Override
                    public void onSuccess(BaseInfo<List<OperateFeeduInfo>> baseInfo) {
                        if (baseInfo != null && baseInfo.getData() != null) {

                            String feedu = "";
                            String feeduIds = "";
                            for (OperateFeeduInfo ofi : baseInfo.getData()) {
                                for (OperateFeeduInfo.BasLoadFeeDetailVosBean bfv : ofi.getBasLoadFeeDetailVos()) {
                                    feedu = StringUtils.isCanUse(feedu) ? feedu + "," + bfv.getFeeValue() : bfv.getFeeValue();
                                    feeduIds = StringUtils.isCanUse(feeduIds) ? feedu + "," + bfv.getId() : bfv.getId();
                                }
                            }

                            currentOperate.setFeeIds(feeduIds);
                            currentOperate.setJobConstMoney(feedu);

                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {

                    }
                });
    }
}
